package com.frxuexi.lib_http.download

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import okhttp3.OkHttpClient
import okhttp3.Request
import okio.Sink
import java.io.File

object DownloadUtil {
    fun download(url: String, file: File): Flow<DownloadState> {
        return flow {
            val request = Request.Builder().url(url).get().build()
            val response = OkHttpClient.Builder().build().newCall(request).execute()
            if (response.isSuccessful) {
                response.body.let { b ->
                    file.outputStream().let { os ->
                        val inputStream = b?.byteStream()
                        var bufferLen: Int = 0
                        val byteArray = ByteArray(DEFAULT_BUFFER_SIZE)
                        /* var read = inputStream?.read(byteArray)
                       read?.let {
                            while (it >= 0) {
                                os.write(byteArray, 0, it)
                                bufferLen += it
                                read = inputStream?.read(byteArray)
                            }
                            emit(DownloadState.onSuccess)
                        }*/
                        while (inputStream?.read(byteArray).also { bufferLen = it!! } != -1) {
                            os.write(byteArray, 0, bufferLen)
                        }
                        os.flush()
                        os.close()

                        // 下载完成
                        emit(DownloadState.onSuccess)
                    }
                }
            }else{
                emit(DownloadState.onError(response.message))
            }
        }
    }
}